package com.cx330.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cx330.order.bean.Order;
import com.cx330.order.feign.ProductFeignClient;
import com.cx330.order.service.OrderService;
import com.cx330.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long userId, Long productId) {
//        Product product = getProductFromRemote(productId);
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        // 总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("上海");
        // 远程查询商品列表
        order.setProductList(Arrays.asList(product));
//        try {
//            SphU.entry("haha");
//        } catch (BlockException e) {
//            // 编码处理
//        }
        return order;
    }

    // 兜底回调
    public Order createOrderFallback(Long userId, Long productId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息：" + e.getClass());
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        // 1. 获取到商品服务所在的所有机器IP + port
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//        ServiceInstance instance = instances.get(0);
//        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
//        ServiceInstance choose = loadBalancerClient.choose("service-product");
//        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/product/" + productId;
//        log.info("远程调用：{}", url);
        String url = "http://service-product/product/" + productId;
        // 2. 给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
